package cn.oowoo.rabbitmq.returnListener;

import cn.oowoo.rabbitmq.config.RabbitConfig;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @Author ZhangBin
 * @Date 2021/5/8 13:48
 * @Description: 消息退回-生产者
 *  测试额外参数传递、消息过期时间等
 **/
public class ReturnListenerProducer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = RabbitConfig.createConnection();
        // 创建消息通道
        Channel channel = connection.createChannel();
        //监听无法路由的消息
        channel.addReturnListener(new ReturnListener() {
            public void handleReturn(int replyCode,
                                     String replyText,
                                     String exchange,
                                     String routingKey,
                                     AMQP.BasicProperties properties,
                                     byte[] body) throws IOException {
                System.out.println("=========监听器收到了无法路由，被返回的消息============");
                System.out.println("replyText:"+replyText);
                System.out.println("exchange:"+exchange);
                System.out.println("routingKey:"+routingKey);
                System.out.println("message:"+new String(body,"UTF-8"));
                System.out.println();
            }
        });

        for(int i=0;i<10;i++){
            String msg =  "测试不可达消息...." + i;
            String routingKey = RabbitConfig.ROUTING_RETURNLISTENER_KEY;
            if( i == 3 || i == 6 || i == 9){
                routingKey = RabbitConfig.ROUTING_RETURNLISTENER_KEY_1;
            }
            /*
             void basicPublish(String exchange, String routingKey, boolean mandatory, BasicProperties props, byte[] body)
             mandatory， 设置为true，则监听器会接收到路由不可达的消息， 然后进行处理，如果设置为false，那么broker端自动删除该消息不会进入addReturnListener.handleReturn方法
             消息发送到了的交换机上，由于没有任何队列使用这个关键字跟交换机绑定，所以会被退回
            */
            channel.basicPublish(RabbitConfig.EXCHANGE_RETURNLISTENER_NAME, routingKey, true,null, msg.getBytes());
        }

        //消息发送完毕关闭信道，关闭链接 (不关闭链接，查看addlistener监听到的消息)
        //channel.close();
        //connection.close();
    }
}
